package com.my.es.test.doc;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.my.es.test.pojo.User;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: TODO
 * @date 2024/5/9 16:39
 */
public class ESTest_Doc_Insert_Batch {

    public static void main(String[] args) throws IOException {
        RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
        
        // 插入数据
        BulkRequest request = new BulkRequest();

        IndexRequest userRequest1 = new IndexRequest().index("user").id("1001")
                .source(XContentType.JSON, "name", "zhangsan", "age", 30, "sex", "男");

        IndexRequest userRequest2 = new IndexRequest().index("user").id("1002")
                .source(XContentType.JSON, "name", "lisi", "age", 40, "sex", "女");

        IndexRequest userRequest3 = new IndexRequest().index("user").id("1003")
                .source(XContentType.JSON, "name", "wangwu0", "age", 50, "sex", "女");

        IndexRequest userRequest4 = new IndexRequest().index("user").id("1004")
                .source(XContentType.JSON, "name", "wangwu1", "age", 60, "sex", "男");

        IndexRequest userRequest5 = new IndexRequest().index("user").id("1005")
                .source(XContentType.JSON, "name", "wangwu2", "age", 70, "sex", "男");

        IndexRequest userRequest6 = new IndexRequest().index("user").id("1006")
                .source(XContentType.JSON, "name", "wangwu3", "age", 80, "sex", "男");

        request.add(userRequest1);
        request.add(userRequest2);
        request.add(userRequest3);
        request.add(userRequest4);
        request.add(userRequest5);
        request.add(userRequest6);


        BulkResponse response = esClient.bulk(request, RequestOptions.DEFAULT);
        System.out.println("response.getIngestTookInMillis() = " + response.getIngestTookInMillis());
        System.out.println("response.getItems() = " + response.getItems());


        esClient.close();
    }
    
}
